const md5 = (str) => {
    const crypto = require('crypto');
    const md5Opt = crypto.createHash('md5');
    md5Opt.update(str);
    return md5Opt.digest('hex');
}
const apiToken = () => {
    const { apiKey } = require('../config');
    const time = Date.parse(new Date()) / 1000;
    return {
        request_time: time,
        request_token: md5(time.toString() + md5(apiKey))
    };
}
const checkPort = (port = NaN) => {
    if (!isNaN(port) && port >= 0 && port <= 65535) {
        return true;
    } else {
        return false;
    }
}
const checkIp = (ip = '') => {
    let reg = /^((25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(25[0-5]|2[0-4]\d|[01]?\d\d?)$/;
    return reg.test(ip);
}

const formatTime=(obj,dateType='Y-m-d H:i:s')=>{
    let t = typeof obj == 'string' ? new Date(obj.replace(/-/g, "/")) : new Date(obj);
    let Y = t.getFullYear();
    let m = t.getMonth() + 1;
    let d = t.getDate();
    let h = t.getHours();
    let i = t.getMinutes();
    let s = t.getSeconds();
    m = m < 10 ? '0' + m : m;
    d = d < 10 ? '0' + d : d;
    h = h < 10 ? '0' + h : h;
    i = i < 10 ? '0' + i : i;
    s = s < 10 ? '0' + s : s;
    let time = Y + '-' + m + '-' + d + ' ' + h + ':' + i + ':' + s;
    if (typeof dateType != 'undefined' && dateType != '') {
        switch (dateType) {
            case 'Y-m-d H:i:s':
                time = Y + '-' + m + '-' + d + ' ' + h + ':' + i + ':' + s;
                break;
            case 'Y-m-d H:i':
                time = Y + '-' + m + '-' + d + ' ' + h + ':' + i;
                break;
            case 'Y-m-d H':
                time = Y + '-' + m + '-' + d + ' ' + h;
                break;
            case 'Y-m-d':
                time = Y + '-' + m + '-' + d;
                break;
            case 'YmdHis':
                time = Y + '' + m + '' + d + '' + h + '' + i + '' + s;
                break;
            default:
                time = Y + '-' + m + '-' + d + ' ' + h + ':' + i;
                break;
        }
    }
    return time;
}

module.exports = {
    md5,
    apiToken,
    checkPort,
    checkIp,
    formatTime
}